package com.ruoyi.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IBusinessUserService;

/**
 * 商家用户关联服务实现
 * 
 * @author ruoyi
 */
@Service
public class BusinessUserServiceImpl implements IBusinessUserService
{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Long getDefaultBusinessIdByUserId(Long userId)
    {
        try {
            System.out.println("=== 开始查询用户ID: " + userId + " 的商家关联信息 ===");
            
            // 先测试数据库连接
            try {
                String testSql = "SELECT COUNT(*) FROM business_user_relation";
                Integer count = jdbcTemplate.queryForObject(testSql, Integer.class);
                System.out.println("数据库连接测试成功，business_user_relation表记录数: " + count);
            } catch (Exception e) {
                System.out.println("数据库连接测试失败: " + e.getMessage());
                e.printStackTrace();
                return null;
            }
            
            // 查询默认商家关联
            String sql1 = "SELECT business_id FROM business_user_relation WHERE user_id = ? AND is_default = 1 AND status = 1 ORDER BY create_time DESC LIMIT 1";
            System.out.println("执行SQL1: " + sql1 + " 参数: " + userId);
            
            try {
                Long businessId = jdbcTemplate.queryForObject(sql1, Long.class, userId);
                System.out.println("找到默认商家ID: " + businessId);
                return businessId;
            } catch (Exception e1) {
                System.out.println("未找到默认商家，尝试查询所有商家关联");
                System.out.println("异常信息: " + e1.getMessage());
                
                // 如果没有默认商家，查询第一个商家关联
                String sql2 = "SELECT business_id FROM business_user_relation WHERE user_id = ? AND status = 1 ORDER BY is_default DESC, create_time DESC LIMIT 1";
                System.out.println("执行SQL2: " + sql2 + " 参数: " + userId);
                
                try {
                    Long businessId = jdbcTemplate.queryForObject(sql2, Long.class, userId);
                    System.out.println("找到商家ID: " + businessId);
                    return businessId;
                } catch (Exception e2) {
                    System.out.println("未找到任何商家关联");
                    System.out.println("异常信息: " + e2.getMessage());
                    return null;
                }
            }
        } catch (Exception e) {
            System.out.println("查询商家关联信息失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
} 